import 'dart:async';
import 'dart:convert';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';

class ImageUtils {
  /// 从base64加载图片
  static Future<ui.Image?> loadImageFromBase64(String base64Data) async {
    try {
      var data = base64Decode(base64Data);
      final Completer<ui.Image> completer = Completer();
      ui.decodeImageFromList(data, (ui.Image img) {
        if (!completer.isCompleted) {
          completer.complete(img);
        }
      });
      final image = await completer.future.timeout(Duration(seconds: 5));
      return image;
    } catch (e) {
      if (kDebugMode) {
        print('加载图片失败: $e');
      }
      return null;
    }
  }

  /// 从Base64加载图片并应用指定颜色
  static Future<ui.Image?> loadImageFromBase64WithColor(
    String base64Data,
    Color color, {
    double? width,
    double? height,
  }) async {
    try {
      // 1. 解码Base64数据
      final data = base64Decode(base64Data);

      // 2. 将字节数据解码为原始图片
      final Completer<ui.Image> originalCompleter = Completer();
      ui.decodeImageFromList(data, (ui.Image img) {
        if (!originalCompleter.isCompleted) {
          originalCompleter.complete(img);
        }
      });

      // 设置超时
      final originalImage = await originalCompleter.future.timeout(
        const Duration(seconds: 5),
        onTimeout: () => throw TimeoutException('加载图片超时'),
      );

      // 3. 确定最终要使用的宽高
      final targetWidth = width?.toInt() ?? originalImage.width;
      final targetHeight = height?.toInt() ?? originalImage.height;

      // 4. 创建带颜色过滤和指定尺寸的新图片
      return _applyColorFilterAndResize(
        originalImage,
        color,
        targetWidth,
        targetHeight,
      );
    } catch (e) {
      if (kDebugMode) {
        print('处理图片失败: $e');
      }
      return null;
    }
  }

  /// 应用颜色过滤并调整图片尺寸
  static Future<ui.Image> _applyColorFilterAndResize(
    ui.Image image,
    Color color,
    int targetWidth,
    int targetHeight,
  ) async {
    // 创建一个指定尺寸的画布
    final recorder = ui.PictureRecorder();
    final canvas = Canvas(recorder);

    // 创建颜色过滤 - 使用srcIn模式保留原图alpha通道，替换颜色
    final paint = Paint()
      ..colorFilter = ColorFilter.mode(color, BlendMode.srcIn);

    // 在画布上绘制图片并应用颜色过滤和尺寸调整
    canvas.drawImageRect(
      image,
      Rect.fromLTWH(0, 0, image.width.toDouble(), image.height.toDouble()),
      Rect.fromLTWH(0, 0, targetWidth.toDouble(), targetHeight.toDouble()),
      paint,
    );

    // 结束录制并转换为图片
    final picture = recorder.endRecording();
    return picture.toImage(targetWidth, targetHeight);
  }

  /// 将PNG图片转换为Base64
  static Future<String?> imageToBase64(ui.Image image) async {
    try {
      // 将图像编码为字节数据
      ByteData? byteData = await image.toByteData(
        format: ui.ImageByteFormat.png,
      );
      if (byteData == null) {
        throw Exception('无法将图像编码为字节数据');
      }
      // 转换为Uint8List
      final Uint8List uint8List = byteData.buffer.asUint8List();
      // 编码为Base64字符串
      return base64Encode(uint8List);
    } catch (e) {
      if (kDebugMode) {
        print('图像转换为Base64失败: $e');
      }
      return null;
    }
  }
}
